package org.hardstone.controller;

import org.hardstone.domain.BaseItemDomain;
import org.hardstone.service.BaseService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

public abstract class BaseController<T extends BaseItemDomain<PK>, PK extends Serializable, M extends BaseService<T,PK>> {
    protected M service;
    protected PK id;
    public BaseController(M service) {
        this.service = service;
    }

    @RequestMapping("/findById/{id}")
    ResponseEntity<T> findById(@PathVariable("id") PK id) {
        try {
            T result = service.findById(id).get();
            if (result.equals(new Object())) {
                return ResponseEntity.notFound().build();
            }else {
                return ResponseEntity.ok(result);
            }
        }catch (NoSuchElementException e){
            return ResponseEntity.notFound().build();
        }
    }

    @RequestMapping("findAll")
    ResponseEntity<List<T>> findAll() {
        try {
            List<T> list = new ArrayList<>();
            for (T item : service.findAll()) {
                list.add(item);
            }
            return ResponseEntity.ok(list);
        } catch (NoSuchElementException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @RequestMapping("/deleteById/{id}")
    ResponseEntity<String> deleteById(@PathVariable("id") PK id) {
        try {
            service.deleteById(id);
            return ResponseEntity.ok("True");
        } catch (NoSuchElementException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @RequestMapping("/count")
    ResponseEntity<String> count() {
        try {
            PK pk = service.count();
            return ResponseEntity.ok(pk.toString());
        } catch (NoSuchElementException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @RequestMapping("/deleteAll")
    ResponseEntity<String> deleteAll() {
        try {
            service.deleteAll();
            return ResponseEntity.ok("True");
        } catch (NoSuchElementException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping("/create")
    ResponseEntity<T> create(@RequestBody T entity) {
        try {
            T t = service.save(entity);
            return ResponseEntity.ok(t);
        } catch (NoSuchElementException e) {
            return ResponseEntity.notFound().build();
        }
    }




}
